import { createFromIconfontCN } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Space, Switch } from 'antd';
import React, { useEffect, useState } from 'react';
const ThemeSwitch: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const MyIcon = createFromIconfontCN({
    scriptUrl: initialState?.settings?.iconfontUrl, // 在 iconfont.cn 上生成
  });
  const [defaultChecked, setdefaultChecked] = useState(false);
  useEffect(() => {
    const navTheme = localStorage.getItem('ThemeSwitch');
    if (navTheme) {
      setdefaultChecked(navTheme === 'realDark');
    }
  }, [defaultChecked]);
  const onChange = (checked: boolean) => {
    const navTheme = checked ? 'realDark' : 'light';
    const setting: any = initialState?.settings;
    setting.navTheme = navTheme;
    setInitialState((s) => ({ ...s, setting, time: new Date().getTime() }));
    localStorage.setItem('ThemeSwitch', navTheme);
    setdefaultChecked(navTheme === 'realDark');
  };
  return (
    <Space>
      <Switch
        checkedChildren={<MyIcon type="icon-ClearNight-qing-yewan" style={{ fontSize: '22px' }} />}
        unCheckedChildren={<MyIcon type="icon-Sunny-qing-baitian" style={{ fontSize: '22px' }} />}
        checked={defaultChecked}
        onChange={onChange}
      />
    </Space>
  );
};
export default ThemeSwitch;
